/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import com.codemagi.util.Utils;
import javax.servlet.http.HttpServletRequest;

/**
 * If the input is an Integer, check that it is less than the maximum set at initialization time
 */
public class IntegerMaximumValidator implements IValidator {

    private int maximum;

    private static final String MSG_OVER_MAXIMUM = "The value entered exceeds the maximum allowed.";

    public IntegerMaximumValidator(int newMaximum) {
	maximum = newMaximum;
    }

    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	//sanity check
	if (Utils.isEmpty(obj)) return obj;

	if (obj instanceof Integer && ((Integer)obj).intValue() > maximum) throw new AppException(MSG_OVER_MAXIMUM);

	return obj;
    }

}
